// import store from "../store/index.js";

const tips = {
	1: '抱歉，出现了一个错误',
	3: '请求接口失败',
	5: '网络错误'
}

function _show_error(error_code) {
	if (!error_code) {
		error_code = 1
	}
	const tip = tips[error_code]
	wx.showToast({
		title: tip ? tip : tips[1],
		icon: 'none',
		duration: 2000
	})
}
export function getNewToken() {
	return store.dispatch('login')
}
export function getToken() {
	return uni.getStorageSync('userToken')
}
// # 解构
export default function request({ url, data = {}, method, dataType = 'json', token }) {
	return new Promise((resolve, reject) => {
		//判断token是否过期
		let timestamp_now = Math.round(new Date() / 1000)
		let timestamp = parseInt(uni.getStorageSync('timestamp'))
		if(timestamp_now-timestamp>3000){
			getNewToken().then(res => {
			}).then(() => {
				_request( url, resolve, reject, data, method, dataType)
			})
		}else{
			_request( url, resolve, reject, data, method, dataType)
		}
	})
}

function _request(url, resolve, reject, data = {}, method, dataType = 'json', token){
	// uni.showLoading({
	//     title: '正在加载',
	// 		mask: true
	// });
	uni.request({
		url:'https://xdjzapi.towngo.cn/'+url,
		// url:'https://xdjzapi.towngo.cn/'+url,
		// url:'http://z.zhejiangshudie.com/'+url
		data:data,
		method:method,
		timeout:15000,
		header:{
			// 'Authorization':'Bearer ' + store.getters.getToken
			'Authorization':'Bearer ' + getToken()
		},
		success: (res) => {
			const code = res.data.status_code
			const resData = res.data
			if(res.statusCode!==200){
				uni.showToast({
					title:res.data.message,
					icon:'none'
				})
			}
			//token过期或无效
			if(parseInt(code) === 410){
				uni.removeStorageSync('userToken');
				uni.navigateTo({
					url: '/user/login/index'
				});
			}else {
				resolve(resData)
				return
			}

		},
		fail: (f) => {
			uni.showToast({
				title:'您当前网络不佳,请稍后再试',
				icon:'none'
			})
			// uni.showModal({
			// 	title:'提示',
			// 	showCancel:false,
			// 	content:'网络繁忙,请稍后再试'
			// })
		}
	})
}

// 把获取到的数据过滤一遍
const replaceNull = (obj) => {
    for (let key in obj) {
        switch (Object.prototype.toString.call(obj[key]).slice(8, -1)) {
            case 'Object':
                replaceNull(obj[key])
                break;
            case 'Array':
                for (let i = 0; i < obj[key].length; i++){
                    replaceNull(obj[key][i])
                }
                break;
            default:
                if (obj[key] === null) obj[key] = undefined;
        }
    }
}
